//
//  SCRadioPlayView.m
//  LastOne
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 sc. All rights reserved.
//

#import "SCRadioPlayView.h"
#import <UIImageView+WebCache.h>
#import "SCRadioModel.h"
#import "SCRadioPlayTableViewCell.h"
#import "NightHeader.h"
#import "Music.h"
#import "HTTPMethod.h"
#import "SCPlayRadio.h"
#import "FitHeader.h"
@implementation SCRadioPlayView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //播放标示符
        [Music shareInstance].flag = 1;
        //获取单例的manager对象赋值给当前VC的manager
        _manager = [CoreDataManager shareManager];
        
        
        //背景图
        _bigImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 200 * FitHeight)];
        _bigImageView.userInteractionEnabled = YES;
        [self addSubview:_bigImageView];
   
        //正在播放label
        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 375 * FitWidth, 27 * FitHeight)];
        _nameLabel.backgroundColor = [UIColor grayColor];
        _nameLabel.alpha = .5;
        [_bigImageView addSubview:_nameLabel];
        _nameLabel.textColor = [UIColor whiteColor];
        //上一曲
        _upImageView = [[UIImageView alloc] initWithFrame:CGRectMake(60 * FitWidth, 85 * FitHeight, 40 * FitWidth, 40 * FitWidth)];
        _upImageView.layer.cornerRadius = 20 * FitWidth;
        _upImageView.layer.masksToBounds = YES;
        _upImageView.image = [UIImage imageNamed:@"shangyiqu"];
        [_bigImageView addSubview:_upImageView];
        _upImageView.backgroundColor = [UIColor clearColor];
        //上一曲点击方法
        _upImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *upTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(UpTapAction)];
        [_upImageView addGestureRecognizer:upTap];
        
        //转盘
        _bigPlayImageView = [[UIImageView alloc] initWithFrame:CGRectMake(_upImageView.frame.origin.x + _upImageView.frame.size.width + 20 * FitWidth, 30 * FitHeight, 110 * FitWidth, 110 * FitWidth)];
        _bigPlayImageView.layer.borderWidth = 10;
        _bigPlayImageView.layer.borderColor = [UIColor darkGrayColor].CGColor;
        _bigPlayImageView.layer.masksToBounds = YES;
        _bigPlayImageView.layer.cornerRadius = 55 * FitWidth;
        [_bigImageView addSubview:_bigPlayImageView];
        _bigPlayImageView.image = [UIImage imageNamed:@"placeholder"];
        //为转盘添加手势
        _bigPlayImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *playTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playAndPauseAction:)];
        [_bigPlayImageView addGestureRecognizer:playTap];
        
        //播放按钮
        _palyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(152 * FitWidth, 65 * FitHeight, 44 * FitWidth, 44 * FitWidth)];
        _palyImageView.layer.masksToBounds = YES;
        _palyImageView.layer.cornerRadius = 22 * FitWidth;
        _palyImageView.image = [UIImage imageNamed:@"bofang"];
        _palyImageView.backgroundColor = [UIColor redColor];
        _palyImageView.alpha = .8;
        [_bigImageView addSubview:_palyImageView];
        
        //下一曲按钮
        _downImageView = [[UIImageView alloc] initWithFrame:CGRectMake(_bigPlayImageView.frame.origin.x + _bigPlayImageView.frame.size.width + 20 * FitWidth, _upImageView.frame.origin.y, _upImageView.frame.size.width, _upImageView.frame.size.height)];
        _downImageView.image = [UIImage imageNamed:@"xiayiqu"];
        _downImageView.layer.cornerRadius = 20 * FitWidth;
        _downImageView.layer.masksToBounds = YES;
        [_bigImageView addSubview:_downImageView];
        _downImageView.backgroundColor = [UIColor clearColor];
        _downImageView.userInteractionEnabled = YES;
        //添加方法
        UITapGestureRecognizer *downTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(DownTapAction)];
        [_downImageView addGestureRecognizer:downTap];
        
       _playTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(30 * FitWidth, _bigPlayImageView.frame.origin.y + _bigPlayImageView.frame.size.height + 5 * FitHeight, 50 * FitWidth, 20 * FitHeight)];
        _playTimeLabel.text = @"00:00";
        _playTimeLabel.font = [UIFont systemFontOfSize:14 * FitWidth];
       _playTimeLabel.textColor = [UIColor whiteColor];
       [_bigImageView addSubview:_playTimeLabel];
        //滑块控制
        _slider = [[UISlider alloc] initWithFrame:CGRectMake(_playTimeLabel.frame.origin.x + _playTimeLabel.frame.size.width, _bigPlayImageView.frame.origin.y + _bigPlayImageView.frame.size.height + 10 * FitHeight, 200 * FitWidth, 5 * FitHeight)];
        [_bigImageView addSubview:_slider];
        
        _AllTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(_slider.frame.origin.x + _slider.frame.size.width, _playTimeLabel.frame.origin.y, _playTimeLabel.frame.size.width, _playTimeLabel.frame.size.height)];
        _AllTimeLabel.text = @"00:00";
        _AllTimeLabel.font = [UIFont systemFontOfSize:14 * FitWidth];
        _AllTimeLabel.textColor = [UIColor whiteColor];
        [_bigImageView addSubview:_AllTimeLabel];
        
        _slider.minimumValue = 0;
        _slider.maximumValue = 1;
        _slider.minimumTrackTintColor = [UIColor whiteColor];
       [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playing) userInfo:nil repeats:YES];
       // [self.slider addTarget:self action:@selector(slideValueChanged:) forControlEvents:UIControlEventValueChanged];
        
        //初始化tableView
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _bigImageView.frame.origin.y + _bigImageView.frame.size.height, self.frame.size.width, self.frame.size.height - _bigImageView.frame.size.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView NightWithType:UIViewColorTypeNormal];
        _tableView.tableFooterView = [[UITableView alloc] init];
        [self addSubview:_tableView];
        
        
        //转盘动画效果
        _basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        _basicAnimation.fromValue = [NSNumber numberWithInteger:0];
        // 一个M_PI半圈
        _basicAnimation.toValue = [NSNumber numberWithInteger:M_PI * 200];
        [_basicAnimation setDuration:200];
        [_basicAnimation setRepeatCount:NSIntegerMax]; //NSIntegerMax
    }
    return self;
}

- (void)setRadioModel:(SCRadioModel *)radioModel
{
    if (_radioModel != radioModel) {
        //添加图片
        [_bigPlayImageView sd_setImageWithURL:[NSURL URLWithString:radioModel.imgsrc] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    }
}

- (void)setDataSourceArray:(NSMutableArray *)dataSourceArray
{
    if (_dataSourceArray != dataSourceArray) {
        _dataSourceArray = dataSourceArray;
    }
    [_tableView reloadData];
    
    //进入该页面默认播第一个节目
    [self getData:0];
    _songFlag = 0;
    _nameLabel.text = [NSString stringWithFormat:@"正在播放: %@", [_dataSourceArray[0] title]];
     _palyImageView.image = [UIImage imageNamed:@"zanting"];
    [_bigPlayImageView.layer addAnimation:_basicAnimation forKey:@"rotation"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70 * FitHeight;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    SCRadioPlayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[SCRadioPlayTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = NO;
    cell.radioModel = _dataSourceArray[indexPath.row];
    cell.timeLabel.textType = [NSNumber numberWithFloat:LabelColorGray];
    [cell.timeLabel NightWithType:UIViewColorTypeNormal];
    [cell NightWithType:UIViewColorTypeNormal];
    [cell.titleLabel NightWithType:UIViewColorTypeNormal];
    
    return cell;
}

#pragma mark - tableView的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _songFlag = indexPath.row;
    _nameLabel.text = [NSString stringWithFormat:@"正在播放: %@", [_dataSourceArray[indexPath.row] title]];
    [self getData:indexPath.row];
}

#pragma mark - 音频的数据解析
- (void)getData:(NSInteger)row
{
   [HTTPMethod getDataByString:[NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html", [_dataSourceArray[row] docid]] BodyDic:nil WithDataBlock:^(id data) {
       
       SCPlayRadio *playRadio = [NSEntityDescription insertNewObjectForEntityForName:@"SCPlayRadio" inManagedObjectContext:_manager.managedObjectContext];
       
       SCPlayRadioModel *playRadioModel = [[SCPlayRadioModel alloc] init];
       NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[[[data objectForKey:[_dataSourceArray[row] docid]] objectForKey:@"video"] objectAtIndex:0]];
       
       [playRadioModel setValuesForKeysWithDictionary:dic];
       //播放视频
       [[Music shareInstance] playMusicWith:playRadioModel.url_mp4];
       //添加图片
       [_bigPlayImageView sd_setImageWithURL:[NSURL URLWithString:playRadioModel.cover] placeholderImage:[UIImage imageNamed:@"placeholder"]];
       
       playRadio.url_mp4 = playRadioModel.url_mp4;
       playRadio.cover = playRadioModel.cover;
       playRadio.alt = playRadioModel.alt;
       
       [_manager saveContext];
   }];
}

#pragma mark - 播放和暂停
- (void)playAndPauseAction:(UITapGestureRecognizer *)tap
{
    if ([Music shareInstance].flag == 1) {
        _palyImageView.image = [UIImage imageNamed:@"bofang"];
        [[Music shareInstance].player pause];
        [_bigPlayImageView.layer removeAllAnimations];
        [Music shareInstance].flag = 0;
    }
    else{
        _palyImageView.image = [UIImage imageNamed:@"zanting"];
        [[Music shareInstance].player play];
        [_bigPlayImageView.layer addAnimation:_basicAnimation forKey:@"rotation"];
        [Music shareInstance].flag = 1;
    }
}
#pragma mark - 上一曲
- (void)UpTapAction
{
    if (_songFlag != 0) {
        --_songFlag;
    }
    [self getData:_songFlag];
    _nameLabel.text = [NSString stringWithFormat:@"正在播放: %@", [_dataSourceArray[_songFlag] title]];
}

#pragma mark - 下一曲 
- (void)DownTapAction
{
    if (_songFlag < _dataSourceArray.count - 1) {
        ++_songFlag;
    }
    [self getData:_songFlag];
    _nameLabel.text = [NSString stringWithFormat:@"正在播放: %@", [_dataSourceArray[_songFlag] title]];
}


-(void)playing
{
    NSTimeInterval avPlayTime = [self playableCurrentTime];
    self.playTimeLabel.text = [self convertToMM:avPlayTime];
    NSTimeInterval durTime = [self playableDuration];
    self.AllTimeLabel.text = [self convertToMM:durTime];
    CGFloat percent = avPlayTime / durTime;
    self.slider.value = percent;
    
    //自动播发下一曲
    if ([[self convertToMM:avPlayTime] isEqualToString:[self convertToMM:durTime]] &&  ![[self convertToMM:avPlayTime] isEqualToString:@"0-2147483648:0-8"]) {
            [self DownTapAction];
    }
}

- (NSTimeInterval)playableDuration
{
    AVPlayerItem * item = [Music shareInstance].player.currentItem;
    if (item.status == AVPlayerItemStatusReadyToPlay) {
        return CMTimeGetSeconds([Music shareInstance].player.currentItem.duration);
    }
    else
    {
        return(CMTimeGetSeconds(kCMTimeInvalid));
    }
}

- (NSTimeInterval)playableCurrentTime
{
    AVPlayerItem * item = [Music shareInstance].player.currentItem;
    if (item.status == AVPlayerItemStatusReadyToPlay) {
        return CMTimeGetSeconds([Music shareInstance].player.currentItem.currentTime);
    }
    else
    {
        return(CMTimeGetSeconds(kCMTimeInvalid));
    }
}

- (NSString*)convertToMM:(NSTimeInterval)t {
    int m = t / 60;
    int s = (int)t % 60;
    NSString* mStr = [NSString stringWithFormat:(m < 10 ? @"0%d" : @"%d"),m];
    NSString* sStr = [NSString stringWithFormat:(s < 10 ? @"0%d" : @"%d"),s];
    return [NSString stringWithFormat:@"%@:%@",mStr,sStr];
}
//- (void)slideValueChanged:(UISlider*)slider {
//    double t = [self playableDuration] * slider.value;
//    if(t > 0)
//    {
//        if ([[self convertToMM:t] isEqualToString:[self convertToMM:[self playableCurrentTime]]]) {
//            NSLog(@"fds");
//            [self DownTapAction];
//        }
//       // self.playTimeLabel.text = [self convertToMM:t];
//        [[Music shareInstance].player seekToTime:CMTimeMakeWithSeconds((t), 44100)];
//    }
//}

@end
